package cn.schoolwow.quickdao.module.database.dml.existQuery.flow.instance;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.sql.ResultSet;
import java.util.Arrays;

public class GetInstanceCountByIdFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setStatement(flowContext);
        setParameters(flowContext);
        executeStatement(flowContext);
    }

    @Override
    public String name() {
        return "根据id字段查询记录个数";
    }

    private void setStatement(FlowContext flowContext) {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        Entity entity = flowContext.checkData("entity", Entity.class);
        DatabaseProvider databaseProvider = flowContext.checkInstanceData(DatabaseProvider.class);
        
        String key = "selectCountById_" + entity.tableName + "_" + databaseProvider.name();
        if (!quickDAOConfig.databaseContext.statementCache.containsKey(key)) {
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append("select count(1) from " + databaseProvider.escape(entity.tableName) + " where ");
            sqlBuilder.append(databaseProvider.escape(entity.id.column) + " = ?");
            quickDAOConfig.databaseContext.statementCache.put(key, sqlBuilder.toString());
        }
        String sql = quickDAOConfig.databaseContext.statementCache.get(key);
        flowContext.putTemporaryData("sql", sql);
    }

    private void setParameters(FlowContext flowContext) {
        Entity entity = flowContext.checkData("entity", Entity.class);
        Object instance = flowContext.checkData("instance");

        Object idValue = QueryInstance.newQuery(instance)
                .execute()
                .getSingleFieldValue(entity.id.name);
        flowContext.putTemporaryData("parameters", Arrays.asList(idValue));
    }

    private void executeStatement(FlowContext flowContext){
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "根据Id字段查询记录个数")
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        if(resultSet.next()){
                            flowContext.putData("count", resultSet.getLong(1));
                        }
                    }
                })
                .execute();
    }

}
